package com.lqian.demo01.wait_notify;

import com.lqian.utils.SleepHelper;

import java.util.Queue;

/**
 * wait 和 notify 生产者消费者模型
 */
public class Producer implements Runnable{
    private Queue<String> bags;
    private int size;

    public Producer(Queue<String> bags, int size) {
        this.bags = bags;
        this.size = size;
    }

    @Override
    public void run() {
        int i = 0;
        while(true){
            i++;
            synchronized (bags){

                while (bags.size() ==size){
                    System.out.println("bags has already full...");
                    // TODO: 2022/7/7  满了 >>> 阻塞
                    try {
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                SleepHelper.sleepSeconds(1); //每一秒钟生产一个
                System.out.println("生产者：生产：bag"+i);
                bags.add("bag-"+i);
                // TODO: 2022/7/7 没满 通知消费者消费 唤醒处于阻塞状态的消费者
                bags.notifyAll();
            }
        }
    }
}
